using UnityEngine;
using UnityEditor;

public class SpriteExportTool
{
    [MenuItem("[FutureCore]/Sprite/导出图集精灵", false, 0)]
    static void SaveSprite()
    {
        foreach (Object obj in Selection.objects)
        {
            string resourcesPath = "Assets/Resources/";
            string selectionPath = AssetDatabase.GetAssetPath(obj);
            string selectionExt = System.IO.Path.GetExtension(selectionPath);
            if (selectionExt.Length == 0) continue;

            string loadPath = selectionPath.Remove(selectionPath.Length - selectionExt.Length);
            loadPath = loadPath.Substring(resourcesPath.Length);

            Sprite[] sprites = Resources.LoadAll<Sprite>(loadPath);
            if (sprites.Length > 0)
            {
                string outPath = Application.dataPath + "/$ExportSprite/" + loadPath;
                System.IO.Directory.CreateDirectory(outPath);

                foreach (Sprite sprite in sprites)
                {
                    Texture2D tex = new Texture2D((int)sprite.rect.width, (int)sprite.rect.height, sprite.texture.format, false);
                    tex.SetPixels(sprite.texture.GetPixels((int)sprite.rect.xMin, (int)sprite.rect.yMin,
                                                           (int)sprite.rect.width, (int)sprite.rect.height));
                    tex.Apply();
                    System.IO.File.WriteAllBytes(outPath + "/" + sprite.name + ".png", tex.EncodeToPNG());
                }
            }
        }
        AssetDatabase.Refresh();
        DebugUtil.Log("导出图集精灵完成");
    }
}